package com.example.designpattern.strategy;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

/**
 * 策略模式测试类
 *
 * @author long
 * @date 2024/11/12 13:28
 */
@Service
public class TestStrategyService{

    @Resource
    private IStudyService studyChineseServiceImpl;

    @Resource
    private IStudyService studyMathsServiceImpl;

    @Resource
    private IStudyService studyEnglishServiceImpl;

    /**
     * 处理请求
     * @param studyType
     */
    public void handleRequest(String studyType){

        // 原始逻辑
        oldIfJudge(studyType);

        // 策略模式逻辑
        strategyMode(studyType);
    }

    /**
     * 原始代码
     * @param studyType
     */
    private void oldIfJudge(String studyType){
        if("chinese".equals(studyType)){
            studyChineseServiceImpl.doStudy(studyType);
        }else if("maths".equals(studyType)){
            studyMathsServiceImpl.doStudy(studyType);
        }else if("english".equals(studyType)){
            studyEnglishServiceImpl.doStudy(studyType);
        }
    }


    @Autowired
    private List<IStudyService> studyServiceList;

    /**
     * 策略模式
     * @param studyType
     *
     * 参考 依赖注入
     * @see AbstractAutowireCapableBeanFactory#populateBean(java.lang.String, org.springframework.beans.factory.support.RootBeanDefinition, org.springframework.beans.BeanWrapper)
     */
    private void strategyMode(String studyType){
        for(IStudyService studyService : studyServiceList){
            // 类型是否匹配，匹配到后走对应的逻辑
            if(Objects.equals(studyType,studyService.studyLanguage().getCode())){
                studyService.doStudy(studyType);
            }
        }

    }

}
